import { createRouter, createWebHistory } from "vue-router";
import { ElMessage } from "element-plus";
import { h } from "vue";

const routes = [
  //登录页路由
  {
    path: "/login",
    name: "登录页",
    component: () => import("../views/Login.vue"),
  },
  // 页面找不到404 路由
  {
    path: "/404",
    name: "NoPage 404",
    component: () => import("../views/404.vue"),
    hidden: true,
  },
  {
    path: "/:pathMatch(.*)",
    redirect: "/404",
    hidden: true,
  },
  //框架布局路由
  {
    path: "/",
    name: "框架页",
    component: () => import("../views/Index.vue"),
    redirect: "/home",
    children: [
      {
        path: "/home",
        name: "home",
        component: () => import("../views/Home.vue"),
      },
      {
        path: "/classes",
        name: "classes",
        component: () => import("../views/stu/Classes.vue"),
      },
      {
        path: "/student",
        name: "student",
        component: () => import("../views/stu/Student.vue"),
      }
    ],
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

// 设置登录过期时间（一天）86400000
let expire = 86400000;

//路由守卫
//全局守卫，登录拦截
//进行路由拦截：当没有登陆标识，直接打回登陆页面，如何避免退回到 登陆页呢？
router.beforeEach((to, from, next) => {
  // 从本地缓存中获取保存的 token 信息
  const tokenObj = JSON.parse(window.localStorage.getItem("isLogin"));
  if (to.path == "/login") {
    next();
  } else {
    // 如果没有token，强制跳转到登录页面；如果有，则判断token时间是否过期
    if (!tokenObj || !tokenObj.token) {
      next("/login");
      ElMessage({
        type: "warning",
        message: "非法访问,请登录!",
        duration: 2000,
      });
    } else {
      let date = new Date().getTime();
      // 当前时间 - token中的登录时间 > 设置的过期时间，为过期；则清除token，并强制跳转至登录页
      // 反之为有效期，则放行
      if (date - tokenObj.startTime > expire) {
        window.localStorage.removeItem("isLogin");
        next("/login");
        ElMessage({
          type: "warning",
          message: "登录状态过期,请重新登录!",
          duration: 2000,
        });
      } else {
        next();
      }
    }
  }
});

export default router;
